package ru.aptu.billing_client;

import ru.aptu.billing_message.RequestMessage;
import ru.aptu.billing_message.ResponseMessage;
import ru.aptu.socket_factory.BillingSocketFactory;
import ru.aptu.socket_factory.ConnectionChecker;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 12/23/11
 * Time: 1:45 AM
 */
public class BillingClient {

    protected int port;

    protected String host;

    ObjectInputStream objectInputStream;

    ObjectOutputStream objectOutputStream;

    public BillingClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public boolean initConnection() {
        try {
            Socket socket = BillingSocketFactory.createSocket(port, host);

            ConnectionChecker.checkClientConnection(socket);

            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectInputStream = new ObjectInputStream(socket.getInputStream());
        } catch (IOException ex) {
            return false;
        }

        return true;
    }

    public void close() {
        try {
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            objectInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public ResponseMessage sendMessage(RequestMessage message) {
        try {
            objectOutputStream.writeObject(message);
            return (ResponseMessage) objectInputStream.readObject();
        } catch (IOException e) {
            System.err.println("Error sending/receiving message.");
        } catch (ClassNotFoundException e) {
            System.err.println("Error serializing message.");
        }
        return null;
    }

}
